﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace 街头篮球自动购买道具
{
    public partial class frmMain : Form
    {
        private bool isNext;        // 是否获取下一用户
        private bool isPause;
        private int webIndex;
        private int userIndex;
        private MyHtmlTools myHtml;

        public frmMain()
        {
            InitializeComponent();
        }

        #region 识别验证码
        /// <summary>
        /// 识别验证码
        /// </summary>
        /// <param name="img">验证码图片</param>
        /// <returns></returns>
        private string DiscernPic2Text(Image img)
        {
            Image targetImage = JpgColor2BlackAndWhite.WhiteAndBlack(img);
            return CompareBmp(targetImage);
        }

        /// <summary>
        /// 开始图片对比
        /// </summary>
        private string CompareBmp(Image img)
        {
            string result = string.Empty;
            // 循环获取4个数字
            for (int i = 0; i < 4; i++)
            {
                Bitmap sourceBmp = new Bitmap(9, 13);
                Graphics sourceGraphics = Graphics.FromImage(sourceBmp);
                Rectangle sourceRect = new Rectangle(7 + i * 13, 3, 9, 13);
                sourceGraphics.DrawImage(img, 0, 0, sourceRect, GraphicsUnit.Pixel);

                // 循环对比10个数字
                for (int j = 0; j < 10; j++)
                {
                    Image testImg = Image.FromFile(Application.StartupPath + @"\code.dll");
                    Bitmap targetBmp = new Bitmap(9, 13);
                    Graphics targetGraphics = Graphics.FromImage(targetBmp);
                    Rectangle targetRect = new Rectangle(j * 9, 0, 9, 13);
                    targetGraphics.DrawImage(testImg, 0, 0, targetRect, GraphicsUnit.Pixel);
                    if (JpgColor2BlackAndWhite.CompareBmp(sourceBmp, targetBmp))
                    {
                        result += j.ToString();
                    }
                }
            }
            return result;
        }
        #endregion

        /// <summary>
        /// 导入账号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsbtnImport_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "文本文件|*.txt";

            DialogResult result = openFileDialog.ShowDialog();
            if (result == DialogResult.OK)
            {
                if (openFileDialog.FileName != "")
                {
                    lvUsers.Items.Clear();
                    string strFileContent = TextManager.OpenFile(openFileDialog.FileName);
                    string[] strArray = strFileContent.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (string tmpValue in strArray)
                    {
                        string[] tmpStr = tmpValue.Split(' ');
                        string strUserName = tmpStr[0];
                        string strUserPwd = tmpStr[1];

                        ListViewItem item = new ListViewItem(strUserName);
                        item.Tag = strUserPwd;
                        lvUsers.Items.Add(item);
                    }
                }
            }
        }

        /// <summary>
        /// 登录用户
        /// </summary>
        private void loginGameWeb(string userName, string userPwd)
        {
            HtmlElement elementUserName = myHtml.GetElementByType("input", "text");
            HtmlElement elementUserPwd = myHtml.GetElementByType("input", "password");
            HtmlElement elementLogin = myHtml.GetElementByID("login");

            elementUserName.SetAttribute("value", userName);
            elementUserPwd.SetAttribute("value", userPwd);

            elementLogin.InvokeMember("click");
        }

        private void webBrowse_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            webIndex++;
            switch (webBrowse.Document.Title)
            {
                case "天游通行证－登陆":
                    if (webIndex == 1)
                    {
                        loginGameWeb(lvUsers.Items[userIndex].Text, lvUsers.Items[userIndex].Tag.ToString());
                    }
                    else
                    {
                        isNext = true;
                    }
                    break;
                case "登录天游通行证":
                    isNext = true;
                    break;
                case "天游道具商城-宝石交易系统":
                    HtmlElement htmlMoney = myHtml.GetElementByID("baoshi_balance");
                    txtMoney.Text = htmlMoney.GetAttribute("value");
                    // 跳转到商品详细
                    webBrowse.Navigate(cboUrl.Text);
                    break;
                case "天游道具商城-商品详细":
                    string strCode = string.Empty;
                    strCode = DiscernPic2Text(myHtml.GetRegCodePic("img"));
                    // 如果验证码未识别成功,重新刷新页面获取新的验证码
                    if (strCode.Length != 4)
                    {
                        webBrowse.Navigate(webBrowse.Url);
                    }
                    HtmlElement htmlCode = myHtml.GetElementByName("checknum");
                    htmlCode.SetAttribute("value", strCode);
                    // 获取购买按钮元素
                    HtmlElementCollection htmlList = webBrowse.Document.GetElementsByTagName("img");
                    HtmlElement buyButton =  GetBuyButton(htmlList);
                    if (buyButton != null)
                    {
                        buyButton.InvokeMember("click");
                    }

                    break;
                case "天游道具商城-购买信息":
                    string tmpDocuemt = webBrowse.Document.Body.InnerText;
                    if (tmpDocuemt.IndexOf("购买失败") > 0)
                    {
                        isNext = true;
                    }
                    else
                    {
                        int tmpIndex = tmpDocuemt.IndexOf("您剩余宝石为:");

                        txtMoney.Text = tmpDocuemt.Substring(tmpIndex, tmpDocuemt.IndexOf('.', tmpIndex) - tmpIndex);
                        // 跳转到商品详细
                        webBrowse.Navigate(cboUrl.Text);
                    }
                    break;
                case "天游游乐场 - 店铺错误":
                    isNext = true;
                    break;
            }
        }

        /// <summary>
        /// 获取购买道具按钮
        /// </summary>
        /// <param name="htmlList"></param>
        /// <returns></returns>
        private HtmlElement GetBuyButton(HtmlElementCollection htmlList)
        {
            HtmlElement obj = null;
            foreach (HtmlElement element in htmlList)
            {
                if (element.OuterHtml.IndexOf("btn_itembuy.jpg") > 0)
                {
                    obj = element;
                    break;
                }
            }
            return obj;
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            LoadUrl();
        }

        /// <summary>
        /// 载入URL到下拉地址栏
        /// </summary>
        private void LoadUrl()
        {
            string strUrl = TextManager.OpenFile(Application.StartupPath + @"\Url.ini");
            string[] tmpArray = strUrl.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            cboUrl.Items.Clear();
            foreach (string tmpStr in tmpArray)
            {
                cboUrl.Items.Add(tmpStr);
            }
            if (cboUrl.Items.Count > 0)
            {
                cboUrl.SelectedIndex = 0;
            }
        }

        /// <summary>
        /// 添加地址
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddUrl_Click(object sender, EventArgs e)
        {
            if (cboUrl.Text != "")
            {
                foreach (object obj in cboUrl.Items)
                {
                    if (obj.ToString() == cboUrl.Text)
                    {
                        return;
                    }
                }
                cboUrl.Items.Add(cboUrl.Text);
            }
        }

        /// <summary>
        /// 删除地址
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelUrl_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < cboUrl.Items.Count; i++)
            {
                if (cboUrl.Items[i].ToString() == cboUrl.Text)
                {
                    cboUrl.Items.RemoveAt(i);
                    break;
                }
            }
        }

        /// <summary>
        /// 保存新URL到文件
        /// </summary>
        private void SaveUrl()
        {
            StringBuilder sb = new StringBuilder();
            foreach (object obj in cboUrl.Items)
            {
                sb.AppendFormat("{0}\r\n", obj.ToString());
            }
            TextManager.SaveFile("Url.ini", sb.ToString(), false);
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            SaveUrl();
        }

        /// <summary>
        /// 开始购买
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsbtnStartBuy_Click(object sender, EventArgs e)
        {
            // 如果没有账号不进行查询
            if (lvUsers.Items.Count == 0)
            {
                MessageBox.Show("请导入查询帐号！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            userIndex = -1;
            isNext = true;
            Timer t = new Timer();
            t.Interval = 500;
            t.Tick += new EventHandler(t_Tick);
            t.Start();
            // 开始查询信息
            DoStartBuy();
            t.Stop();
        }

        void t_Tick(object sender, EventArgs e)
        {
            int hWnd = 0;

            hWnd = AutoCloseWindow.GetPoPupWindowhWndByName("街头篮球自动购买道具");
            // 如果窗体存在
            if (hWnd != 0)
            {
                // 如果是来自网页的消息
                if (AutoCloseWindow.WindowTitle == "来自网页的消息")
                {
                    AutoCloseWindow.DoClick2PopupWindow(hWnd, "确定");
                }
                // 来自网页的确认对话框
                if (AutoCloseWindow.WindowTitle == "来自网页的确认对话框")
                {
                    AutoCloseWindow.DoClick2PopupWindow(hWnd, "确定");
                }
            }
        }

        private void DoStartBuy()
        {
            while (userIndex < lvUsers.Items.Count)
            {
                // 暂停退出循环
                if (isPause) { break; }
                Application.DoEvents();
                if (isNext)
                {
                    webIndex = 0;
                    isNext = false;
                    userIndex++;
                    if (userIndex < lvUsers.Items.Count)
                    {
                        lvUsers.Items[userIndex].Selected = true;
                    }
                    txtMoney.Text = "0";
                    myHtml = new MyHtmlTools(webBrowse);
                    webBrowse.Url = new Uri(@"http://passport.t2cn.com/login/login.jsp?success_url=http%3A%2F%2Fshop.t2cn.com%2Fshop%2FtradeIndex.action");
                }
            }

            if (!isPause) { MessageBox.Show("购买完毕！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); }
        }
    }
}
